package com.zallds.fabric.service.impl;

import com.zallds.fabric.service.myccService;
import com.zallds.fabric.util.*;
import org.apache.log4j.Logger;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;

/**
 * Created by liujian on 2018/9/10.
 */

@Service("myccService")
public class myccServiceImpl implements myccService {

    //日志记录
    private static Logger logger = Logger.getLogger(FabricUtils.class);

    //CA客户端
    public static HFClient client = null;

    public static CryptoSuite cs = null;

    public static HashMap<String, SOrg> orgHashMap = null;

    public static ChaincodeID cid = null;

    public static User peer0org1 = null;

    public static Channel channel = null;

    /**
     * 每次进行操作的时候进行实例化
     *
     * @throws Exception
     */
    public myccServiceImpl() throws Exception {
        cs = CryptoSuite.Factory.getCryptoSuite();
        cid = ChaincodeID.newBuilder().setName("mycc").build();
        client = HFClient.createNewInstance();
        client.setCryptoSuite(cs);
        orgHashMap = OrgConfig.getSOrg();
        peer0org1 = orgHashMap.get("org1").getAdmin();
        client.setUserContext(peer0org1);

        /**
         * 实例化Channel
         */
        channel = client.newChannel(CommonUtils.channelId);
        channel.addPeer(client.newPeer(CommonUtils.peer0Org1Name, CommonUtils.peer0Org1Location, FabricUtils.getPeerProperty("org1.example.com", "peer0.org1.example.com")));
        channel.addOrderer(client.newOrderer(CommonUtils.orderName, CommonUtils.orderLocation, FabricUtils.getOrderProperty()));
        channel.initialize();
    }


    @Override
    public String invoke(String nameA, String nameB, int money) throws InvalidArgumentException, ProposalException {
        // 构建proposal
        TransactionProposalRequest req = client.newTransactionProposalRequest();
        // 指定要调用的chaincode
        ChaincodeID cid = ChaincodeID.newBuilder().setName(CommonUtils.chainCodeName).build();
        req.setChaincodeID(cid);
        req.setFcn("invoke");
        req.setArgs(nameA, nameB, Integer.toString(money));
        // 发送proprosal
        Collection<ProposalResponse> resps = null;
        resps = channel.sendTransactionProposal(req);
        for (ProposalResponse resp : resps) {
            //System.out.println("response: " + resp.getMessage());
            String payload = null;

            payload = new String(resp.getChaincodeActionResponsePayload());

            System.out.println("response: " + payload);
        }

        // 提交给orderer节点
        channel.sendTransaction(resps);
        return "success !!!";
    }


    @Override
    public String queryMoney(String name) throws Exception {
        QueryByChaincodeRequest req = client.newQueryProposalRequest();
        ChaincodeID cid = ChaincodeID.newBuilder().setName("mycc").build();
        req.setChaincodeID(cid);
        req.setFcn("query");
        req.setArgs(new String[]{name});
        try {
            Collection<ProposalResponse> resps = channel.queryByChaincode(req);
            for (ProposalResponse resp : resps) {
                String payload = new String(resp.getChaincodeActionResponsePayload());
                return payload;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
